package com.springcloud.sc.ucpv5.dushanzi.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.springcloud.sc.ucp.v5.api.vo.GroupDO;
import com.springcloud.sc.ucp.v5.api.vo.UserInfoDO;
import com.springcloud.sc.ucpv5.client.application.message.DataMessageManager;
import com.springcloud.sc.ucpv5.client.commondata.MyGroup;
import com.springcloud.sc.ucpv5.client.commondata.MyUser;
import com.springcloud.sc.ucpv5.client.commondata.MyUserInfoData;
import com.springcloud.sc.ucpv5.client.commondata.SecuResult;
import com.springcloud.sc.ucpv5.client.commondata.data.CommonRsp;
import com.springcloud.sc.ucpv5.client.module.datamanager.BaseDataManager;
import com.springcloud.sc.ucpv5.dushanzi.config.util.DuShanZiUtil;
import com.springcloud.sc.ucpv5.service.UcpService;
import com.springcloud.sc.ucpv5.tree.data.WebTreeNode;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/dushanzi")
public class DuShanZiController {

    @Autowired
    private UcpService ucpService;


    //显示分页数据
    @RequestMapping("/findPage")
    public Page findPage(@RequestParam Map<String, Object> params) {
//        String uid =  this.getUserId();
        String uid =  null;
        String userId =String.valueOf(uid);
        String type = String.valueOf( params.get("type") );
        if(type.equals("node")){
            // wsy 20190603 独山子选择节点时,不出现下级子组, 因为普通管理员登录, 只看见自身所在组, 而这个接口节点下会显示非自身所在组
            List list = new ArrayList();
            Page page = new Page();
            page.setTotal(0);
            page.setRecords( list );
            return page;
        }
        Page page =  ucpService.findListById( params , userId, false);
        return page;
    }

    @ApiOperation(value = "获取用户树", notes = "根据当前登录用户")
    @GetMapping(value = "/getTreeByNodeId")
    public List<WebTreeNode> getTreeByNodeId() {
//        String uid =  this.getUserId();
        String uid =  null;
        String userId =String.valueOf(uid);
        List<WebTreeNode> webTreeNodes  = ucpService.getWebListTreeOwnGroup(userId);
        return webTreeNodes;
        /*String jsonStr = JSONObject.toJSONString( webTreeNodes );
        //类似于以数组的方式来返回
        return "["+jsonStr+"]";*/
    }

    @PostMapping(value = "/saveUCPUser")
    public void saveUCPUser(@RequestBody UserInfoDO userInfo) {
        try{
            MyUser myUser = BaseDataManager.getInstance().userGet( userInfo.getUserTelno() );
            if (myUser != null) {
                // wsy 20190603 如果用户已经存在, 则将用户分配到组里
                try{
                    if(userInfo.GrpList != null && !"".equals(userInfo.GrpList)) {
                        // 将用户加入到组里
                        MyGroup group = BaseDataManager.getInstance().groupGet(userInfo.GrpList);
                        if(group != null){
                            ArrayList<String> addList = new ArrayList<String>();
                            addList.add(userInfo.getUserTelno());
                            ArrayList<String> delList = new ArrayList<String>();
                            SecuResult secuResult = DataMessageManager.getInstance().dealGroupUserOneByOne(group, addList, delList);
                        }
                    }
                }catch (Exception ex){
                    ex.printStackTrace();
                }
                return;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        ucpService.saveUserInfo( userInfo );
    }

    @PostMapping("/updateUser")
    public boolean updateNode( @RequestBody UserInfoDO userInfo  ){
        // 用户出现修改优先级为0的情况, 需要做特殊判断处理

      return  ucpService.updateUserInfo( userInfo );
    }

    @PostMapping(value = "/delUCPUser")
    public void delUCPUser(@RequestBody UserInfoDO userInfo) {
        try{
            MyUser myUser = BaseDataManager.getInstance().userGet(userInfo.getUserTelno());
            List<MyGroup> groupList = myUser.getGroupList();
            if(groupList.size() > 1){
                // 当用户存在多个组时, 只对用户做组分配出去的动作
                MyGroup group = BaseDataManager.getInstance().groupGet(userInfo.getGrpList());
                if(group != null){
                    ArrayList<String> addList = new ArrayList<String>();
                    ArrayList<String> delList = new ArrayList<String>();
                    delList.add(userInfo.getUserTelno());
                    SecuResult secuResult = DataMessageManager.getInstance().dealGroupUserOneByOne(group, addList, delList);
                    return;
                }
            }
            else{
                this.ucpService.deleteUserInfo(userInfo.getUserTelno());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        ucpService.saveUserInfo( userInfo );
    }


    @PostMapping("/saveGroup")
    public void saveGroup( @RequestBody GroupDO groupDO  ){
        // wsy 20190603 独山子建立组的时候, 组号码采用自动生成
        try{
            // 先判断父组是否存在
            MyGroup parentGroup = BaseDataManager.getInstance().groupGet(groupDO.getParGrpTelno());
            if(parentGroup != null){
                String groupNumber = DuShanZiUtil.根据父组号码获取子组号码(parentGroup);
                if(groupNumber != null && !"".equals(groupNumber)){
                    groupDO.setGroupTelno(groupNumber);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        ucpService.saveGroup(groupDO);
    }

    @PostMapping("/updateGroup")
    public void updateGroup( @RequestBody GroupDO groupDO  ){
        ucpService.updateGroup(groupDO);
    }

    @PostMapping("/distributionGroup")
    public Map DistributionGroup( @RequestBody Map<String, Object> params){
        boolean bool =  ucpService.DistributionGroup(params);
        Map map = new HashMap();
        if (bool){
            map.put("code","1000");
            map.put("result","1000");
        }else{
            map.put("code","2000");
            map.put("result","2000");
        }
        return map;
    }

    @PostMapping("/delete")
    public Map delete(@RequestParam Map<String, Object> params) {
//        String uid =  this.getUserId();
        String uid =  null;
        boolean bool = this.ucpService.delete( params , uid );
        Map map = new HashMap();
        if (bool){
            map.put("code","1000");
            map.put("result","1000");
        }else{
            map.put("code","2000");
            map.put("result","2000");
        }
        return map;
    }

    @RequestMapping("/getGroup")
    public GroupDO getGroup( @RequestParam Map<String, Object> params ){
        GroupDO groupDO = ucpService.getGroup( params );
        return groupDO;
    }
    @RequestMapping("/getUser")
    public UserInfoDO getUser( @RequestParam Map<String, Object> params ){
        UserInfoDO userInfoDO = ucpService.getUser( params );
        return userInfoDO;
    }

    @RequestMapping("/getUserByGroupNumber/{groupNumber}")
    public List getUserByGroupNumber(@PathVariable String groupNumber){
        List list = ucpService.getUserByGroupNumber(groupNumber);
        return list;
    }

    @PostMapping("/voiceAuthoritySet")
    public Map voiceAuthoritySet(@RequestParam Map<String, Object> params) {
        // 用户语音发布权限指定
        String userNumber = String.valueOf(params.get("userNumber"));
        String groupNumber  = String.valueOf(params.get("groupNumber"));
        String voiceAuthority  = String.valueOf(params.get("voiceAuthority"));
        Map map = new HashMap();
        boolean bool = true;
        try{
            MyUser user = BaseDataManager.getInstance().userGet(userNumber);
            if(user != null){
                    MyGroup group = BaseDataManager.getInstance().groupGet(groupNumber);
                    if (group.isYingJiZu()) {
                        // 判断用户是否外线用户
                        if (user.isOutUser()) {
                            // 判断用户优先级
                            MyUserInfoData userInfoData = user.getMyUserInfoData_copy();
                            if(voiceAuthority.equals("false")) {
                                userInfoData.otherInfo.voiceAuthorityGroupList.remove(group.getIdlData().GroupTelno);
                            }
                            else {
                                // 需要调用通用方法判断该用户是否在不同的组里,且组的编号是存在定义一致的
                                String errorInfo = DuShanZiUtil.检查用户在应急组中是否存在组编号冲突(groupNumber, user.getUserInfoData().otherInfo.voiceAuthorityGroupList);
                                if(errorInfo.equals("")) {
                                    userInfoData.otherInfo.voiceAuthorityGroupList.add(group.getIdlData().GroupTelno);
                                }
                                else{
                                    map.put("code","2000");
                                    map.put("result",errorInfo);
                                    bool = false;
                                }
                            }
                            // 修改前, 父组号码带上
                            userInfoData.userInfo.GrpList = groupNumber;
                            CommonRsp rsp = new CommonRsp();
                            SecuResult result = DataMessageManager.getInstance().userModify(user.getPhysicsNodeNumber(), user.getLogicNodeNumber(), userInfoData,
                                    rsp, false, false);
                            if(result.getRetCode() == 0){
                                bool = true;
                            }
                            else{
                                bool = false;
                                map.put("code","2000");
                                map.put("result", "用户修改失败");
                            }
                        }
                        else{

                            bool = false;
                            map.put("code","2000");
                            map.put("result", "非外线用户");

                        }
                    }
                    else{

                        bool = false;
                        map.put("code","2000");
                        map.put("result", "非应急组内操作");
                    }
            }
        }catch(Exception e){
            bool = false;
            map.put("code","2000");
            map.put("result",e.getMessage());
            e.printStackTrace();
        }

        if (bool){
            map.put("code","0");
            map.put("result","成功");
        }
        return map;
    }
}
